/**
 * 线程同步例程：通过实例对象进行线程同步的例程
 */
package thread;

public class J_BlockData extends Thread {
    public int m_ID;
    public J_Experiment4 m_data;

    public J_BlockData(int id) {
        m_ID = id;
    }

    @Override
    public void run() {
        System.out.println("运行线程：" + m_ID);
        synchronized (m_data) {
            m_data.mb_method1(m_ID);
            m_data.mb_method2(m_ID);

        }
    }

    public static void main(String args[]) {
        int n = 10;
        J_BlockData[] t = new J_BlockData[n];
        J_Experiment4 d = new J_Experiment4();

        for (int i = 0; i < n; i++) {
            t[i] = new J_BlockData(i);
            t[i].m_data = d;
            t[i].start();
        }
        System.out.println("方法main结束");
    }
}

class J_Experiment4 {
    public static void mb_sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            System.out.println("异常 InterruptedException：" + e);
            e.printStackTrace();
        }
    }

    public void mb_method1(int id) {
        System.out.printf("线程 %1$d 进入同步方法1\r\n", id);
        mb_sleep(100);
        System.out.printf("线程 %1$d 离开同步方法1\r\n", id);
    }

    public void mb_method2(int id) {
        System.out.printf("线程 %1$d 进入同步方法2\r\n", id);
        mb_sleep(100);
        System.out.printf("线程 %1$d 离开同步方法2\r\n", id);
    }
}
